package com.test.aop;

import com.hustcad.plm.pdm.downloadcenter.model.vo.DownloadOptionVO;
import com.hustcad.plm.pdm.file.model.vo.DownloadDocVO;
import com.hustcad.plm.pdm.partbom.dto.InsertPartDTO;
import com.test.constant.TestErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Aspect
@Component
public class BeforeService {

    @Before(value = "execution(* com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService.insertPart(..))")
    public void beforeAddPart(JoinPoint jp) {
        log.info(">>>>>>>>>>>>>>>>>start beforeAddPart");
        Object[] args = jp.getArgs();
        log.info("args================" + Arrays.toString(args));
        InsertPartDTO insertPartDTO = null;
        for (Object arg : args) {
            if (arg instanceof InsertPartDTO) {
                insertPartDTO = (InsertPartDTO) arg;
                break;
            }
        }
        log.info("insertPartDTO================" + insertPartDTO);
        if (insertPartDTO != null) {
            String partNumber = insertPartDTO.getPartNumber();
            log.info("partNumber================" + partNumber);
            if (partNumber == null) {
                throw TestErrorCodeEnum.PART_NUMBER_NULL_ERROR.getException();
            }
            // 判断编码是否以大写字母开头
            if (!Character.isUpperCase(partNumber.charAt(0))) {
                throw TestErrorCodeEnum.PART_NUMBER_CHECK_FIRST_ERROR.getException();
            }
        }
        log.info(">>>>>>>>>>>>>>>>>end beforeAddPart");
    }

    @Before(value = "execution(* com.hustcad.plm.pdm.downloadcenter.service.TyplmFileDownCenterService.batchDownloadFileByDocList(..))")
    public void beforeBatchDownloadFileByDocList(JoinPoint jp) {
        Object[] args = jp.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        DownloadOptionVO downloadOptionVO = (DownloadOptionVO) args[0];
        if (downloadOptionVO == null) {
            return;
        }
        List<DownloadDocVO> downloadDocList = downloadOptionVO.getDownloadDocList();
        if (downloadDocList == null || downloadDocList.isEmpty()) {
            return;
        }
        DownloadDocVO downloadDocVO = downloadDocList.get(0);
        downloadOptionVO.setZipFileName(
                downloadDocVO.getDocName() + "_" + downloadDocVO.getDocNumber() + "_" + downloadDocVO.getDocTypeName() + ".zip");
        log.info("zipFileName==============" + downloadOptionVO.getZipFileName());
    }
}
